//
//  FLRestorePurchaseViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/4.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "FLRestorePurchaseViewController.h"
#import "FLPagingScrollViewController.h"
#import "FLVideoDrawViewController.h"
#import "FLRecordedViewController.h"
#import "JDLTabBarController.h"
#import "AppDelegate.h"
#import "FLAddView.h"
#import "JDLTabBarController.h"
#import "FLUseofTermsViewController.h"
#import "FLPrivacypolicyViewController.h"
#import "FLPrivacyAgreement.h"
#import <StoreKit/StoreKit.h>
#import "AppDelegate.h"
#import "FLRestorePurchaseViewController.h"

@interface FLRestorePurchaseViewController ()
<SKPaymentTransactionObserver,UITextViewDelegate,SKProductsRequestDelegate,UIScrollViewDelegate>
{
     FLAddView * _addview;
    FLPrivacyAgreement * privacyAgreement;
     UILabel * jiagelabel;
}
@property (nonatomic, strong) UIScrollView * oeeScrollView;

@property (nonatomic, strong) UIButton * lijigoumaiButton;
@property (nonatomic, strong) UIButton * yinsizhengceButton;
@property (nonatomic, strong) UIButton * huifugoumaiButton;
@property (nonatomic, strong) UIButton * yonghuxieyiButton;

@property (nonatomic, strong)UITextView * detaile ;
@end

@implementation FLRestorePurchaseViewController
- (void)drawLineByImageView:(UIImageView *)imageView {
    UIGraphicsBeginImageContext(imageView.frame.size);   //开始画线 划线的frame
    [imageView.image drawInRect:CGRectMake(0, 0, imageView.frame.size.width, imageView.frame.size.height)];
    //设置线条终点形状
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    
    CGContextRef line = UIGraphicsGetCurrentContext();
    // 设置颜色
    CGContextSetStrokeColorWithColor(line, [UIColor colorWithHexString:@"#616B75"].CGColor);
    
    
    CGFloat lengths[] = {5,2};//先画4个点再画2个点
    CGContextSetLineDash(line,0, lengths,2);//注意2(count)的值等于lengths数组的长度
    
    CGContextMoveToPoint(line, 0.0, 2.0);    //开始画线
    CGContextAddLineToPoint(line,imageView.frame.size.width,2.0);
    CGContextStrokePath(line);
    // UIGraphicsGetImageFromCurrentImageContext()返回的就是image
    UIImage *image =   UIGraphicsGetImageFromCurrentImageContext();
    imageView.image = image;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [[NSUserDefaults standardUserDefaults] setObject:@"FLRestorePurchaseViewController" forKey:@"currentController"];
    UIImageView * beijing = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"付费背景"]];
    beijing.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) ;
    [self.view addSubview:beijing];
    self.oeeScrollView  = [[UIScrollView  alloc]init];
    self.oeeScrollView.directionalLockEnabled = YES ;
    self.oeeScrollView.showsHorizontalScrollIndicator = NO;
    self.oeeScrollView.showsVerticalScrollIndicator = NO;
    self.oeeScrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault ;
    self.oeeScrollView.alwaysBounceHorizontal = NO;
    self.oeeScrollView.alwaysBounceVertical = NO;
    self.oeeScrollView.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT);
    self.oeeScrollView.delegate = self ;
    //self.oeeScrollView.bounces = false;
    self.oeeScrollView.scrollEnabled = YES;
    self.oeeScrollView.backgroundColor = [UIColor clearColor];
    
    self.oeeScrollView.contentSize = CGSizeMake(0, SCREENHEIGHT/667*750);

    [self.view addSubview:self.oeeScrollView];
    
//    UIImageView * ImageViewtwo = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"付费背景"]];
//    if (SCREENHEIGHT>800) {
//       ImageViewtwo.frame = CGRectMake(0, -45, SCREENWIDTH, SCREENHEIGHT/667*750+85);
//    }else{
//       ImageViewtwo.frame = CGRectMake(0, -20, SCREENWIDTH, SCREENHEIGHT/667*750+20);
//    }
//
//    [self.oeeScrollView addSubview:ImageViewtwo];
    
    
    UILabel * one = [[UILabel alloc]init];
    one.frame = CGRectMake(0, 82*SCREENHEIGHT/667, SCREENWIDTH, 25);
    one.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    one.textAlignment = NSTextAlignmentCenter;
    one.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    one.text = NSLocalizedString(@"oneoneone", nil);
    [self.oeeScrollView addSubview:one];
    
    UIImageView * line1 =[[UIImageView alloc]init];
    line1.frame = CGRectMake(15, 128*SCREENHEIGHT/667-3, SCREENWIDTH-30, 5);
    
    [self.oeeScrollView addSubview:line1];
    [self drawLineByImageView:line1];
    
    UILabel * two = [[UILabel alloc]init];
    two.frame = CGRectMake(0, 144*SCREENHEIGHT/667, SCREENWIDTH, 25);
    two.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    two.textAlignment = NSTextAlignmentCenter;
    two.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    two.text = NSLocalizedString(@"twotwotwo", nil);
    [self.oeeScrollView addSubview:two];
    
    
    
    UILabel * three = [[UILabel alloc]init];
    three.frame = CGRectMake(0, 184*SCREENHEIGHT/667, SCREENWIDTH, 20);
    three.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    three.textAlignment = NSTextAlignmentCenter;
    three.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    three.text = NSLocalizedString(@"threethreethree", nil);
    [self.oeeScrollView addSubview:three];
    
    UILabel * four = [[UILabel alloc]init];
    four.frame = CGRectMake(0,three.bottom, SCREENWIDTH, 20);
    four.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    four.textAlignment = NSTextAlignmentCenter;
    four.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    four.text = NSLocalizedString(@"fourfourfour", nil);
    [self.oeeScrollView addSubview:four];
    
    UILabel * five = [[UILabel alloc]init];
    five.frame = CGRectMake(0,four.bottom, SCREENWIDTH, 20);
    five.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    five.textAlignment = NSTextAlignmentCenter;
    five.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    five.text = NSLocalizedString(@"fivefivefive", nil);
    [self.oeeScrollView addSubview:five];
    
    
    UIImageView * line2 =[[UIImageView alloc]init];
    line2.frame = CGRectMake(60, 254*SCREENHEIGHT/667-3, SCREENWIDTH-120, 5);
    
    [self.oeeScrollView addSubview:line2];
    [self drawLineByImageView:line2];
    
    UILabel * six = [[UILabel alloc]init];
    six.frame = CGRectMake(0, 270*SCREENHEIGHT/667, SCREENWIDTH, 25);
    six.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    six.textAlignment = NSTextAlignmentCenter;
    six.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    six.text = NSLocalizedString(@"sixsixsix", nil);
    [self.oeeScrollView addSubview:six];
    
    
    UILabel * seven = [[UILabel alloc]init];
    seven.frame = CGRectMake(0,310*SCREENHEIGHT/667, SCREENWIDTH, 20);
    seven.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    seven.textAlignment = NSTextAlignmentCenter;
    seven.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    seven.text = NSLocalizedString(@"sevensevenseven", nil);
    [self.oeeScrollView addSubview:seven];
    
    UILabel * eight = [[UILabel alloc]init];
    eight.frame = CGRectMake(0,seven.bottom, SCREENWIDTH, 20);
    eight.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    eight.textAlignment = NSTextAlignmentCenter;
    eight.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    eight.text = NSLocalizedString(@"eighteighteight", nil);
    [self.oeeScrollView addSubview:eight];
    
    
    
    
    
    
    UIImageView * line3 =[[UIImageView alloc]init];
    line3.frame = CGRectMake(60, 360*SCREENHEIGHT/667-3, SCREENWIDTH-120, 5);
    
    [self.oeeScrollView addSubview:line3];
    [self drawLineByImageView:line3];
    
    UILabel * nine = [[UILabel alloc]init];
    nine.frame = CGRectMake(0, 381*SCREENHEIGHT/667, SCREENWIDTH, 25);
    nine.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    nine.textAlignment = NSTextAlignmentCenter;
    nine.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    nine.text = NSLocalizedString(@"nineninenine", nil);
    [self.oeeScrollView addSubview:nine];
    
    UILabel * ten = [[UILabel alloc]init];
    ten.frame = CGRectMake(0,421*SCREENHEIGHT/667, SCREENWIDTH, 20);
    ten.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    ten.textAlignment = NSTextAlignmentCenter;
    ten.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    ten.text = NSLocalizedString(@"tententen", nil);
    [self.oeeScrollView addSubview:ten];
    
    UILabel * eleven = [[UILabel alloc]init];
    eleven.frame = CGRectMake(0,ten.bottom, SCREENWIDTH, 20);
    eleven.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 14];
    eleven.textAlignment = NSTextAlignmentCenter;
    eleven.textColor = [UIColor colorWithRed:177/255.0 green:154/255.0 blue:218/255.0 alpha:1.0];
    eleven.text = NSLocalizedString(@"eleveneleveneleven", nil);
    [self.oeeScrollView addSubview:eleven];
    
    
    UIImageView * line4 =[[UIImageView alloc]init];
    line4.frame = CGRectMake(60, 471*SCREENHEIGHT/667-3, SCREENWIDTH-120, 5);
    
    [self.oeeScrollView addSubview:line4];
    [self drawLineByImageView:line4];
    
    
    _huifugoumaiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _huifugoumaiButton.backgroundColor = [UIColor clearColor];
    [_huifugoumaiButton setTitleColor:[UIColor colorWithHexString:@"#B19ADA"] forState:UIControlStateNormal];
    _huifugoumaiButton.titleLabel.font =[UIFont fontWithName:@"PingFang-SC-Regular" size:12];
    
    [_huifugoumaiButton setTitle:NSLocalizedString(@"huifugoumai", nil) forState:UIControlStateNormal];
    _huifugoumaiButton.titleLabel.numberOfLines = 0;
    [_huifugoumaiButton addTarget:self action:@selector(huifugoumaiButtonClick:) forControlEvents:UIControlEventTouchUpInside];
  
    _huifugoumaiButton.frame = CGRectMake(0, 520*SCREENHEIGHT/667, SCREENWIDTH, 17);
    [self.oeeScrollView addSubview:_huifugoumaiButton];
    
    self.lijigoumaiButton = [UIButton new];
    self.lijigoumaiButton.frame = CGRectMake(15, 544*SCREENHEIGHT/667, SCREENWIDTH-30, 60);
    self.lijigoumaiButton.backgroundColor = [UIColor colorWithHexString:@"#6027C4"];
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = CGRectMake(0,0,SCREENWIDTH-30,60);
    gl.startPoint = CGPointMake(0.07, 0);
    gl.endPoint = CGPointMake(0.94, 1);
    gl.colors = @[(__bridge id)[UIColor colorWithRed:252/255.0 green:88/255.0 blue:143/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:246/255.0 green:55/255.0 blue:49/255.0 alpha:1.0].CGColor];
    gl.locations = @[@(0), @(1.0f)];
    gl.cornerRadius = 30;
    [self.lijigoumaiButton.layer insertSublayer:gl atIndex:0];
    self.lijigoumaiButton.layer.cornerRadius = 30;
    self.lijigoumaiButton.clipsToBounds = YES;
    self.lijigoumaiButton.titleLabel.font =  [UIFont fontWithName:@"PingFangSC-Medium" size: 20];
    [self.lijigoumaiButton setTitleEdgeInsets:UIEdgeInsetsMake(-11, 0, 0, 0)];
    [self.lijigoumaiButton addTarget:self action:@selector(lijigoumai:) forControlEvents:UIControlEventTouchUpInside];
    [self.lijigoumaiButton setTitleColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
     [self.oeeScrollView addSubview:_lijigoumaiButton];
    
    jiagelabel = [[UILabel alloc]init];
    jiagelabel.textColor = [UIColor colorWithRed:248/255.0 green:157/255.0 blue:169/255.0 alpha:1.0];
    jiagelabel.textAlignment = NSTextAlignmentCenter;
    jiagelabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 12];
    jiagelabel.frame = CGRectMake(30, 35, self.lijigoumaiButton.width-60, 17);
    [self.lijigoumaiButton addSubview:jiagelabel];
    
    _detaile = [[UITextView alloc] init];
    
    _detaile.editable = NO;
    
    [_detaile.layer setMasksToBounds:YES];
    _detaile.tag = 836913 ;
    _detaile.layer.cornerRadius = 5 ;
    _detaile.delegate = self;
    _detaile.backgroundColor = [UIColor clearColor];
    _detaile.font = [UIFont fontWithName:@"PingFang-SC-Regular" size:9];
    _detaile.textColor = [UIColor colorWithHexString:@"#666666"];
    _detaile.frame = CGRectMake(15, self.lijigoumaiButton.bottom+14, self.oeeScrollView.width-30, 70*SCREENHEIGHT/667);
    [self.oeeScrollView addSubview:_detaile];
    
    
    _yinsizhengceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _yinsizhengceButton.backgroundColor = [UIColor clearColor];
    [_yinsizhengceButton setTitleColor:[UIColor colorWithHexString:@"#B19ADA"] forState:UIControlStateNormal];
    _yinsizhengceButton.titleLabel.font =[UIFont fontWithName:@"PingFang-SC-Regular" size:12];
    
    [_yinsizhengceButton setTitle:NSLocalizedString(@"yinsizhengce", nil) forState:UIControlStateNormal];
    _yinsizhengceButton.titleLabel.numberOfLines = 0;
    [_yinsizhengceButton addTarget:self action:@selector(yinsizhengceButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    CGSize yinsiSize = [NSLocalizedString(@"yinsizhengce", nil) boundingRectWithSize:CGSizeMake(SCREENWIDTH, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:12]} context:nil].size;
    _yinsizhengceButton.frame = CGRectMake(15, 713*SCREENHEIGHT/667, yinsiSize.width, 17);
    [self.oeeScrollView addSubview:_yinsizhengceButton];
    
    
    
    UIView * lineshu =[[UIView alloc]init];
    lineshu.backgroundColor = [UIColor colorWithHexString:@"#666666"];
    lineshu.frame = CGRectMake(15+yinsiSize.width+4, _yinsizhengceButton.top+3, 1, 12);
    [self.oeeScrollView addSubview:lineshu];
    
    
    _yonghuxieyiButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _yonghuxieyiButton.backgroundColor = [UIColor clearColor];
    [_yonghuxieyiButton setTitleColor:[UIColor colorWithHexString:@"#B19ADA"] forState:UIControlStateNormal];
    _yonghuxieyiButton.titleLabel.font =[UIFont fontWithName:@"PingFang-SC-Regular" size:12];
    
    
    [_yonghuxieyiButton setTitle:NSLocalizedString(@"yonghuxieyi", nil) forState:UIControlStateNormal];
    _yonghuxieyiButton.titleLabel.numberOfLines = 0;
    [_yonghuxieyiButton addTarget:self action:@selector(yonghuxieyiButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    CGSize yonghuSize = [NSLocalizedString(@"yonghuxieyi", nil) boundingRectWithSize:CGSizeMake(SCREENWIDTH, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:12]} context:nil].size;
    _yonghuxieyiButton.frame = CGRectMake(15+yinsiSize.width+9,_yinsizhengceButton.top, yonghuSize.width, 17);
    [self.oeeScrollView addSubview:_yonghuxieyiButton];
    
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];
    
    //获取数据
    AVQuery *configQuery = [AVQuery queryWithClassName:@"Ulist"];
    [configQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
        
        
        if (objects.count) {
            
            if ([languageName containsString:@"zh"]) {
                _detaile.text = objects[0][@"content"];
                jiagelabel.text =objects[0][@"price"];
                [_lijigoumaiButton setTitle:objects[0][@"free"] forState:UIControlStateNormal];
                
            }else{
                jiagelabel.text =objects[0][@"priceeng"];
                _detaile.text = objects[0][@"contenteng"];
                [_lijigoumaiButton setTitle:objects[0][@"freeeng"] forState:UIControlStateNormal];
                
            }
            
        }else{
            
            if ([languageName containsString:@"zh"]) {
                jiagelabel.text=@"No free trial period €29.99/week";
                [_lijigoumaiButton setTitle:@"开始使用" forState:UIControlStateNormal];
                self->_detaile.text = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dengyue" ofType:@".txt"] encoding:NSUTF8StringEncoding error:nil];
                
            }else{
                jiagelabel.text = @"No free trial period €29.99/week";
                [_lijigoumaiButton setTitle:@"Buy now" forState:UIControlStateNormal];
                self->_detaile.text = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dengyue1" ofType:@".txt"] encoding:NSUTF8StringEncoding error:nil];
                
            }
            
        }
        
        
    }];
    
   // [self initsecview];
}
-(void)initsecview{
    
    
    privacyAgreement  = [[FLPrivacyAgreement alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    privacyAgreement.cancelBlock = ^(UIButton * button) {
        AppDelegate * app = [UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        
        [UIView animateWithDuration:1.0f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
        
        
        
    };
    __weak typeof(self) weakself = self;
    privacyAgreement.tureBlock = ^(UIButton * button) {
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"secretlistView"];
        __strong __typeof(self) strongSelf = weakself;
        [strongSelf->privacyAgreement removeFromSuperview];
        
        
    };
    if (![[NSUserDefaults standardUserDefaults]objectForKey:@"secretlistView"]) {
        
        
        [self.view addSubview:privacyAgreement];
    }
    
}

-(void)huifugoumaiButtonClick:(UIButton *)sender{
    
    
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    
}
-(void)lijigoumai:(UIButton *)sender{
    [MobClick event:@"feelinggoumai"];
    
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [self selectPrice];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [MobClick event:@"pay-pagepay-page"];
   
}
-(void)viewWillDisappear:(BOOL)animated{
    [MobClick endLogPageView:@"KLSRestorePurchaseViewController"];
    [super viewWillDisappear:animated];
    // 移除观察者
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
-(void)yinsizhengceButtonClick:(UIButton *)sender{
    
    FLPrivacypolicyViewController *vc =[[FLPrivacypolicyViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
-(void)yonghuxieyiButtonClick:(UIButton *)sender{
    
    FLUseofTermsViewController *vc =[[FLUseofTermsViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
}
#pragma mark selectPrice
-(void)selectPrice
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    [MBProgressHUD showMessag:@"Loading" toView:self.view];
    NSArray * transactions = [SKPaymentQueue defaultQueue].transactions;
    if (transactions.count > 0) {
        
        SKPaymentTransaction* transaction = [transactions firstObject];
        if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            return;
        }
    }
    
    
    if ([SKPaymentQueue canMakePayments]) {
        NSLog(@"selectPrice:yes");
        
        
        [self getRequestAppleProduct];
        
    }else{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"selectPrice:not");
    }
}

#pragma mark storePayDelegate
- (void)getRequestAppleProduct
{
    NSArray *productl;
    if (productIds2.length) {
        productl = [[NSArray alloc] initWithObjects:productIds2,nil];
    }
    else
    {
        productl = @[@"chiziputong"];
    }
    
    NSSet *nsset = [NSSet setWithArray:productl];
    
    
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    
    
    [request start];
}

- (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSArray *product = response.products;
    
    
    if([product count] == 0){
        NSLog(@"[product count]:nothing");
        
        return;
        
    }
    
    SKProduct *requestProduct = nil;
    for (SKProduct *pro in product) {
        
        NSLog(@"[pro description]:%@", [pro description]);
        NSLog(@"[pro localizedTitle]:%@", [pro localizedTitle]);
        NSLog(@"[pro localizedDescription]:%@", [pro localizedDescription]);
        NSLog(@"[pro price]:%@", [pro price]);
        NSLog(@"[pro productIdentifier]:%@", [pro productIdentifier]);
        
        
        if([pro.productIdentifier isEqualToString:productIds2]){
            requestProduct = pro;
        }
    }
    
    SKPayment *payment = [SKPayment paymentWithProduct:requestProduct];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}


- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"didFailWithError:error:%@", error);
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showError:@"Load failure" toView:self.view];
}


- (void)requestDidFinish:(SKRequest *)request{
    //    [MBProgressHUD hideHUDForView:self.view animated:YES];
}


- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        
        switch (tran.transactionState) {
                
            case SKPaymentTransactionStatePurchased:
            {
                
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                
                
                NSDate * nextDay= [NSDate dateWithTimeInterval:24*60*60 sinceDate:tran.transactionDate];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                
                
                [dateFormatter setDateFormat:@"yyyy.MM.dd"];
                
                NSString * strDate = [dateFormatter stringFromDate:nextDay];
                
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                
                [user setObject:strDate forKey:@"strDate"];
                
                
                
                AVObject * product = [AVObject objectWithClassName:@"Purchased"];
                [product setObject:@"1" forKey:@"BOOLPurchased"];
                [product saveEventually:^(BOOL succeeded, NSError * _Nullable error) {
                    if (error) {
                        NSLog(@"");
                    }
                }];
                
                [user setObject:@"1" forKey:@"Purchased"];
                
                JDLTabBarController *tabbarVc =[[JDLTabBarController alloc] init];
                tabbarVc.addBlock = ^(UIButton * button) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"add"object:@(0)];
                    _addview = [[FLAddView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
                    _addview.cancelBlock = ^(UIButton * button) {
                        [_addview removeFromSuperview];
                    };
                    _addview.videoBlock = ^(UITapGestureRecognizer * tap) {
                        [_addview removeFromSuperview];
                        tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                        FLVideoDrawViewController  * vc =[[FLVideoDrawViewController alloc]init];
                        
                        [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                        //tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                    };
                    _addview.audioBlock = ^(UITapGestureRecognizer * tap) {
                        
                        [_addview removeFromSuperview];
                        tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                        FLRecordedViewController * vc =[[FLRecordedViewController alloc]init];
                        [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                        // tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                    };
                    [tabbarVc.view.window addSubview:_addview];
                    
                };
                self.view.window.rootViewController =tabbarVc;
                
                
                
                
            }
                break;
            case SKPaymentTransactionStatePurchasing:
                
                break;
            case SKPaymentTransactionStateRestored:
            {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                NSDate * nextDay= [NSDate dateWithTimeInterval:24*60*60 sinceDate:tran.transactionDate];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                
                
                [dateFormatter setDateFormat:@"yyyy.MM.dd"];
                
                NSString * strDate = [dateFormatter stringFromDate:nextDay];
                
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                
                [user setObject:strDate forKey:@"strDate"];
                [user setObject:@"1" forKey:@"Purchased"];
                JDLTabBarController *tabbarVc =[[JDLTabBarController alloc] init];
                tabbarVc.addBlock = ^(UIButton * button) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"add"object:@(0)];
                    _addview = [[FLAddView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
                    _addview.cancelBlock = ^(UIButton * button) {
                        [_addview removeFromSuperview];
                    };
                    _addview.videoBlock = ^(UITapGestureRecognizer * tap) {
                        [_addview removeFromSuperview];
                        tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                        FLVideoDrawViewController  * vc =[[FLVideoDrawViewController alloc]init];
                        
                        [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                        //tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                    };
                    _addview.audioBlock = ^(UITapGestureRecognizer * tap) {
                        
                        [_addview removeFromSuperview];
                        tabbarVc.selectedViewController.hidesBottomBarWhenPushed=YES;
                        FLRecordedViewController * vc =[[FLRecordedViewController alloc]init];
                        [tabbarVc.selectedViewController pushViewController:vc animated:YES];
                        // tabbarVc.selectedViewController.hidesBottomBarWhenPushed=NO;
                    };
                    [tabbarVc.view.window addSubview:_addview];
                    
                };
                self.view.window.rootViewController =tabbarVc;
            }
                break;
            case SKPaymentTransactionStateFailed:
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            default:
                break;
        }
    }
}


- (void)completeTransaction:(SKPaymentTransaction *)transaction
{
    NSString * str=[[NSString alloc]initWithData:transaction.transactionReceipt encoding:NSUTF8StringEncoding];
    
    NSString *environment=[self environmentForReceipt:str];
    
    
    
    
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
    
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
    
    NSString *encodeStr = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    NSString *sendString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", encodeStr];
    NSLog(@"_____%@",sendString);
    NSURL *StoreURL=nil;
    if ([environment isEqualToString:@"environment=Sandbox"]) {
        
        StoreURL= [[NSURL alloc] initWithString: @"https://sandbox.itunes.apple.com/verifyReceipt"];
    }
    else{
        
        StoreURL= [[NSURL alloc] initWithString: @"https://buy.itunes.apple.com/verifyReceipt"];
    }
    
    NSData *postData = [NSData dataWithBytes:[sendString UTF8String] length:[sendString length]];
    
    NSLog(@"++++++%@",postData);
    NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:StoreURL];
    
    [connectionRequest setHTTPMethod:@"POST"];
    [connectionRequest setTimeoutInterval:50.0];//120.0---50.0zl
    [connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
    [connectionRequest setHTTPBody:postData];
    
    
    NSError *error=nil;
    NSData *responseData=[NSURLConnection sendSynchronousRequest:connectionRequest returningResponse:nil error:&error];
    if (error) {
        
        return;
    }
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
    
    
    //  [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
    
    NSString *product = transaction.payment.productIdentifier;
    
    NSLog(@"transaction.payment.productIdentifier++++%@",product);
    
    if ([product length] > 0)
    {
        NSArray *tt = [product componentsSeparatedByString:@"."];
        
        NSString *bookid = [tt lastObject];
        
        if([bookid length] > 0)
        {
            
            NSLog(@"打印bookid%@",bookid);
            
            [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
        }
    }
    
}

-(NSString * )environmentForReceipt:(NSString * )str
{
    str= [str stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
    
    str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    str = [str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    
    str=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    str=[str stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    
    NSArray * arr=[str componentsSeparatedByString:@";"];
    
    
    NSString * environment=arr[2];
    return environment;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
